/**
 * 
 */
package sailing.ui.systemsetting;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import org.jdesktop.application.SingleFrameApplication;

import sailing.entity.BankName;
import sailing.listener.DATA;
import sailing.listener.UI;
import sailing.managers.BankNameManager;
import sailing.ui.AbstractJPanel;
import sailing.ui.base.TopTitlePanel;
import sailing.ui.model.EditBtnCellEditor;
import sailing.ui.model.EditBtnCellRenderer;
import sailing.ui.systemsetting.model.BankAccountTableModel;
import sailing.ui.systemsetting.model.BankNameTableModel;
import cjlite.logger.Logger;
import cjlite.utils.RandomUtils;
import cjlite.utils.Strings;

/**
 * @author ming
 * 
 */
public class BankAccountMgtPanel extends AbstractJPanel {

	private static Logger logger = Logger.thisClass();

	private JTable bankNameTable;
	private JButton addNewBankNameBtn;
	private BankNameTableModel bankNameTableModel;

	private JTable bankAccountTable;
	private JButton addNewBankAccountBtn;
	private BankAccountTableModel bankAccountTableModel;


	/**
	 * @param application
	 */
	public BankAccountMgtPanel(SingleFrameApplication application) {
		super(application);
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.AbstractJPanel#initialPanel()
	 */
	@Override
	protected void initialPanel() {
		this.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		this.setLayout(new BorderLayout(10, 10));

		//this.add(this.getTopTitlePanel(), BorderLayout.NORTH);
		this.add(new TopTitlePanel("银行账户管理"), BorderLayout.NORTH);
		
		this.add(this.getBankAccountPanel(), BorderLayout.CENTER);
		this.add(this.getBottomPanel(), BorderLayout.SOUTH);

	}


	private JPanel getBankAccountPanel() {
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout(10, 10));

		bankAccountTableModel = new BankAccountTableModel(this.getApplication());
		bankAccountTableModel.dataChanged();
		bankAccountTable = new JTable();
		bankAccountTable.setRowHeight(35);
		bankAccountTable.setIntercellSpacing(new Dimension(15, 5));

		bankAccountTable.setModel(bankAccountTableModel);
		DATA.addDataListener(bankAccountTableModel);

		JScrollPane scrollpane = new JScrollPane(bankAccountTable);
		panel.add(scrollpane, BorderLayout.CENTER);
		panel.add(this.getBankAccountMgtSidebarPanel(), BorderLayout.EAST);

		return panel;
	}


	private JPanel getBankAccountMgtSidebarPanel() {
		JPanel panel = new JPanel();
		addNewBankAccountBtn = new JButton();
		addNewBankAccountBtn.setText("添加银行账户");
		addNewBankAccountBtn.setMargin(new Insets(5, 30, 5, 30));
		addNewBankAccountBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				NewBankAccountDialog nbad = new NewBankAccountDialog(getApplication().getMainFrame(), getApplication());
				nbad.setVisible(true);
			}
		});

		JCheckBox showhideEditBtn = new JCheckBox();
		showhideEditBtn.setText("显示/隐藏编辑按钮");

		showhideEditBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JCheckBox cb = (JCheckBox) e.getSource();
				logger.trace("checkbox for bank name is selected[{0}]", cb.isSelected());
				showHideBankAccountTableEditBtn(cb.isSelected());
			}
		});

		Box bv = Box.createVerticalBox();
		bv.add(addNewBankAccountBtn);
		bv.add(Box.createVerticalStrut(20));
		bv.add(showhideEditBtn);
		panel.add(bv);
		return panel;
	}


	protected void showHideBankAccountTableEditBtn(boolean selected) {

	}


	private JPanel getTopTitlePanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEtchedBorder());
		panel.setBackground(titleBgColor);
		panel.add(new JLabel("银行账户管理"));
		return panel;
	}


	private JPanel getBottomPanel() {
		JPanel bottomRoot = new JPanel() {

			@Override
			public Dimension getPreferredSize() {
				return new Dimension(500, 270);
			}


			@Override
			public Dimension getMinimumSize() {
				return new Dimension(500, 270);
			}
		};
		bottomRoot.setLayout(new BorderLayout(10, 10));
		bottomRoot.add(this.getBottomTopPanel(), BorderLayout.NORTH);

		bottomRoot.add(this.getBankNameMgtPanel(), BorderLayout.CENTER);

		return bottomRoot;
	}


	private JPanel getBankNameMgtPanel() {
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout(10, 10));

		bankNameTableModel = new BankNameTableModel(this.getApplication());
		bankNameTableModel.dataChanged();
		bankNameTable = new JTable();
		bankNameTable.setRowHeight(35);
		bankNameTable.setIntercellSpacing(new Dimension(15, 5));

		bankNameTable.setModel(bankNameTableModel);
		DATA.addDataListener(bankNameTableModel);

		JScrollPane scrollpane = new JScrollPane(bankNameTable);
		panel.add(scrollpane, BorderLayout.CENTER);
		panel.add(this.getBankNameMgtSidebarPanel(), BorderLayout.EAST);

		return panel;
	}


	private JPanel getBankNameMgtSidebarPanel() {
		JPanel panel = new JPanel();
		addNewBankNameBtn = new JButton();
		addNewBankNameBtn.setText("添加新银行名称");
		addNewBankNameBtn.setMargin(new Insets(5, 30, 5, 30));
		addNewBankNameBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				Object bankNameObj = JOptionPane.showInputDialog(BankAccountMgtPanel.this, "请输入银行名称：\n\n", "提示",
						JOptionPane.PLAIN_MESSAGE, null, null, null);

				if (bankNameObj == null) {
					// means cancel
					return;
				}
				String bankName = (String) bankNameObj;
				saveBankName(bankName);
			}
		});

		JCheckBox showhideEditBtn = new JCheckBox();
		showhideEditBtn.setText("显示/隐藏编辑按钮");

		showhideEditBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				JCheckBox cb = (JCheckBox) e.getSource();
				logger.trace("checkbox for bank name is selected[{0}]", cb.isSelected());
				showHideBankNameTableEditBtn(cb.isSelected());
			}
		});

		Box bv = Box.createVerticalBox();
		bv.add(addNewBankNameBtn);
		bv.add(Box.createVerticalStrut(20));
		bv.add(showhideEditBtn);
		panel.add(bv);
		return panel;
	}


	protected void showHideBankNameTableEditBtn(boolean selected) {
		this.bankNameTableModel.showEditBtn(selected);
		// this.customerTableModel.fireTableDataChanged();
		this.bankNameTableModel.fireTableStructureChanged();
		if (selected) {
			this.bankNameTable.getColumnModel().getColumn(1).setCellRenderer(new EditBtnCellRenderer("编辑", "删除"));
			EditBtnCellEditor editBtnCell = new EditBtnCellEditor("编辑", "删除");
			editBtnCell.addBtn1Listener(editBankNameAL);
			editBtnCell.addBtn2Listener(deleteBankNameAL);
			this.bankNameTable.getColumnModel().getColumn(1).setCellEditor(editBtnCell);
		}
	}

	ActionListener editBankNameAL = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() instanceof EditBtnCellEditor) {
				EditBtnCellEditor ce = (EditBtnCellEditor) e.getSource();
				if (ce.getCellEditorValue() instanceof BankName) {
					BankName cc = (BankName) ce.getCellEditorValue();
					logger.trace("edit BankName '{0}'", cc.getName());

					Object bankNameObj = JOptionPane.showInputDialog(BankAccountMgtPanel.this, "请输入银行名称：\n\n",
							"编辑银行名称", JOptionPane.PLAIN_MESSAGE, null, null, cc.getName());

					if (bankNameObj == null) {
						// means cancel
						return;
					}

					cc.setName((String) bankNameObj);
					updateBankName(cc);
				}
			}
		}
	};

	ActionListener deleteBankNameAL = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() instanceof EditBtnCellEditor) {
				EditBtnCellEditor ce = (EditBtnCellEditor) e.getSource();
				if (ce.getCellEditorValue() instanceof BankName) {
					BankName cc = (BankName) ce.getCellEditorValue();
					logger.trace("delete BankName '{0}'", cc.getName());

					int result = JOptionPane.showConfirmDialog(BankAccountMgtPanel.this,
							Strings.concat("确定要删除：'", cc.getName(), "' ?"), "提示", JOptionPane.YES_NO_OPTION);
					if (JOptionPane.YES_OPTION == result) {
						BankNameManager bnm = getApplication().getContext().getIoc().getInstance(BankNameManager.class);

						bnm.delete(cc);
						UI.refresh(BankNameTableModel.class);
					}
				}
			}
		}
	};


	protected void saveBankName(String bankName) {
		if (!isBankNameLegal(bankName)) {
			return;
		}

		BankNameManager bnm = this.getApplication().getContext().getIoc().getInstance(BankNameManager.class);

		if (bnm.isExist(bankName)) {
			JOptionPane.showMessageDialog(this, Strings.concat("'", bankName, "' 已经存在，请重新添加。"));
			return;
		}

		BankName bn = new BankName();
		bn.setId(RandomUtils.randomString16());
		bn.setName(bankName);
		bn.setCreateTime(System.currentTimeMillis());
		if (bnm.saveBankName(bn)) {
			JOptionPane.showMessageDialog(BankAccountMgtPanel.this, "添加成功。");
			UI.refresh(BankNameTableModel.class);
		} else {
			JOptionPane.showMessageDialog(BankAccountMgtPanel.this, "添加失败。");
		}
	}


	protected void updateBankName(BankName cc) {
		if (!isBankNameLegal(cc.getName())) {
			return;
		}

		BankNameManager bnm = this.getApplication().getContext().getIoc().getInstance(BankNameManager.class);

		if (bnm.isExist(cc)) {
			JOptionPane.showMessageDialog(this, Strings.concat("'", cc.getName(), "' 已经存在，请重新添加。"));
			return;
		}

		if (bnm.updateBankName(cc)) {
			JOptionPane.showMessageDialog(BankAccountMgtPanel.this, "编辑成功。");
			UI.refresh(BankNameTableModel.class);
		} else {
			JOptionPane.showMessageDialog(BankAccountMgtPanel.this, "编辑失败。");
		}
	}


	private boolean isBankNameLegal(String bankName) {
		if (bankName == null || bankName.trim().length() == 0) {
			JOptionPane.showMessageDialog(this, "名字不合法，请重新添加。");
			return false;
		}

		return true;
	}


	private JPanel getBottomTopPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEtchedBorder());
		panel.setBackground(titleBgColor);
		panel.add(new JLabel("银行名称管理"));
		return panel;
	}

}
